const express = require('express');
const router = express.Router();
const Joi = require('joi');
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');
const { success, error, validationError, notFound, conflict } = require('../../utils/response');

// 输入验证规则
const createCategorySchema = Joi.object({
  name: Joi.string().min(1).max(50).required(),
  description: Joi.string().max(500).optional(),
  color: Joi.string().pattern(/^#[0-9A-Fa-f]{6}$/).optional(),
  icon: Joi.string().max(50).optional()
});

const updateCategorySchema = Joi.object({
  name: Joi.string().min(1).max(50).optional(),
  description: Joi.string().max(500).allow('').optional(),
  color: Joi.string().pattern(/^#[0-9A-Fa-f]{6}$/).optional(),
  icon: Joi.string().max(50).allow('').optional()
});

/**
 * 获取分类列表
 * GET /api/categories
 */
router.get('/', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    const categories = await db.Category.findAll({
      where: { user_id },
      attributes: ['id', 'name', 'description', 'color', 'icon', 'created_at'],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: false
        }
      ],
      // 添加日记数量统计
      attributes: {
        include: [
          [
            db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')),
            'diary_count'
          ]
        ]
      },
      group: ['Category.id'],
      order: [['created_at', 'ASC']]
    });

    return success(res, categories);

  } catch (err) {
    console.error('获取分类列表错误:', err);
    return error(res, '获取分类列表失败', 500);
  }
});

/**
 * 获取分类详情
 * GET /api/categories/:id
 */
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    const category = await db.Category.findOne({
      where: { id, user_id },
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: ['id', 'title', 'diary_date', 'created_at'],
          limit: 10,
          order: [['diary_date', 'DESC']]
        }
      ]
    });

    if (!category) {
      return notFound(res, '分类不存在');
    }

    return success(res, category);

  } catch (err) {
    console.error('获取分类详情错误:', err);
    return error(res, '获取分类详情失败', 500);
  }
});

/**
 * 创建分类
 * POST /api/categories
 */
router.post('/', authenticateToken, async (req, res) => {
  try {
    // 输入验证
    const { error: validationErr, value } = createCategorySchema.validate(req.body);
    if (validationErr) {
      return validationError(res, '输入数据不合法', validationErr.details[0].message);
    }

    const user_id = req.user.id;
    const { name, description, color, icon } = value;

    // 检查分类名称是否重复
    const existingCategory = await db.Category.findOne({
      where: { user_id, name }
    });

    if (existingCategory) {
      return conflict(res, '分类名称已存在');
    }

    // 创建分类
    const category = await db.Category.create({
      user_id,
      name,
      description,
      color: color || '#1890ff',
      icon
    });

    return success(res, category, '分类创建成功', 200);

  } catch (err) {
    console.error('创建分类错误:', err);
    return error(res, '创建分类失败', 500);
  }
});

/**
 * 更新分类
 * PUT /api/categories/:id
 */
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    // 输入验证
    const { error: validationErr, value } = updateCategorySchema.validate(req.body);
    if (validationErr) {
      return validationError(res, '输入数据不合法', validationErr.details[0].message);
    }

    // 查找分类
    const category = await db.Category.findOne({
      where: { id, user_id }
    });

    if (!category) {
      return notFound(res, '分类不存在');
    }

    // 如果要更新名称，检查是否重复
    if (value.name && value.name !== category.name) {
      const existingCategory = await db.Category.findOne({
        where: { user_id, name: value.name, id: { [db.Sequelize.Op.ne]: id } }
      });

      if (existingCategory) {
        return conflict(res, '分类名称已存在');
      }
    }

    // 更新分类
    await category.update(value);

    return success(res, category, '分类更新成功');

  } catch (err) {
    console.error('更新分类错误:', err);
    return error(res, '更新分类失败', 500);
  }
});

/**
 * 删除分类
 * DELETE /api/categories/:id
 */
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    const category = await db.Category.findOne({
      where: { id, user_id }
    });

    if (!category) {
      return notFound(res, '分类不存在');
    }

    // 检查是否有关联的日记
    const diaryCount = await db.Diary.count({
      where: { category_id: id }
    });

    if (diaryCount > 0) {
      return error(res, `该分类下还有 ${diaryCount} 篇日记，无法删除`, 400);
    }

    await category.destroy();

    return success(res, null, '分类删除成功');

  } catch (err) {
    console.error('删除分类错误:', err);
    return error(res, '删除分类失败', 500);
  }
});

/**
 * 获取分类统计信息
 * GET /api/categories/stats
 */
router.get('/stats/summary', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    const stats = await db.Category.findAll({
      where: { user_id },
      attributes: [
        'id',
        'name',
        'color',
        'icon',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'diary_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: false
        }
      ],
      group: ['Category.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']]
    });

    return success(res, stats);

  } catch (err) {
    console.error('获取分类统计错误:', err);
    return error(res, '获取分类统计失败', 500);
  }
});

module.exports = router; 